﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Coding4Fun.Toolkit.Controls;
using eLearning.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.MahasiswaView
{
    public partial class TugasDetailPage : PhoneApplicationPage
    {
        private Tugas selectedTugas;

        public TugasDetailPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.TUGAS))
            {
                selectedTugas = (Tugas)PhoneApplicationService.Current.State[Config.TUGAS];

                if (selectedTugas != null)
                {
                    textBoxCreated.Text = selectedTugas.Awal.ToString("dd/MM/yyyy");
                    textBoxBatas.Text = selectedTugas.Akhir.ToString("dd/MM/yyyy");
                    textBoxJudul.Text = selectedTugas.Judul;
                    textBoxDeskripsi.Text = selectedTugas.Deskripsi;
                    textBoxStatus.Text = selectedTugas.Status == true ? "Sudah mengumpulkan" : "Belum mengumpulkan";
                    buttonUpload.Content = selectedTugas.Status == true ? "Lihat Tugas Saya" : "Kumpulkan Tugas";
                    if (selectedTugas.Akhir.Date < DateTime.Now.Date && !selectedTugas.Status)
                    {
                        buttonUpload.IsEnabled = false;
                        buttonUpload.Content = "Sudah batas akhir";
                    }
                    detailTugas = selectedTugas.DetailTugas;
                }
            }
        }

        private void backButton_Click(object sender, System.EventArgs e)
        {
            if (pivotTugas.SelectedIndex == 1)
                pivotTugas.SelectedIndex = 0;
            else
                NavigationService.GoBack();
        }

        private void pivotTugas_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            
        }

        private void ViewDetailTugas(TugasDetail value)
        {
            if (value != null)
            {
                detailTugas = value;

                pivotTugas.SelectedIndex = 1;
                textBoxSend.Text = value.Sent.ToString("dd/MM/yyyy");
                textBoxLink.Text = value.Link;
            }
        }

        private void buttonUpload_Click(object sender, RoutedEventArgs e)
        {
            if (detailTugas != null && !string.IsNullOrEmpty(detailTugas.Link))
            {
                ViewDetailTugas(detailTugas);
                pivotTugas.SelectedIndex = 1;
            }
            else
            {
                if (MessageBox.Show("Pilih OK jika ingin mengupload tugas, Cancel jika ingin menuliskan link file", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    Utility.GotoPage(this, "/Controls/StorageBrowser.xaml");
                    StorageBrowser.CallerPage(this);
                }
                else
                {
                    InputPrompt prompt = new InputPrompt();
                    prompt.Message = "Masukkan link tugas";
                    prompt.Completed += new EventHandler<PopUpEventArgs<string, PopUpResult>>(prompt_Completed);
                    prompt.InputScope = new InputScope { Names = { new InputScopeName() { NameValue = InputScopeNameValue.Url } } };
                    prompt.Show();
                }
            }
        }

        private void prompt_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            if (!string.IsNullOrEmpty(e.Result))
            {
                DetailTugas().Link = e.Result;
                SaveTugas(DetailTugas());
            }
        }

        public void ReadFile(string fileName, Stream fileStream)
        {
            Dictionary<string[], object> data = new Dictionary<string[], object>()
                    {
                        {new string[]{"uploadedfile", fileName}, FileUtil.ReadToEnd(fileStream)}
                    };

            parameters = data;

            if (MessageBox.Show("Upload file ini sebagai tugas " + selectedTugas.Judul + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                Upload(Config.Instance.UPLOAD_SERVICE_URL() + Config.UPLOAD_TASK_KEY);
            }
        }

        string uploadLink = "";
        string boundary = "----------" + DateTime.Now.Ticks.ToString();
        public Dictionary<string[], object> parameters;
        private TugasDetail detailTugas;

        public void Upload(string url)
        {
            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
            myRequest.Method = "POST";
            myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

            myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            FileUtil.writeMultipartObject(postStream, parameters, boundary);
            postStream.Close();

            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);

            uploadLink = streamRead.ReadToEnd();
            this.Dispatcher.BeginInvoke(() =>
            {
                if (uploadLink.Contains("http://"))
                {
                    DetailTugas().Link = uploadLink;
                    SaveTugas(DetailTugas());
                }
                else
                {
                    MessageBox.Show(uploadLink);
                }
            });

            streamResponse.Close();
            response.Close();
        }

        private void SaveTugas(TugasDetail data)
        {
            string json = null, url = null;

            if (data.Id == null)
            {
                url = Config.Instance.TUGAS_SERVICE_URL() + Config.TUGAS_ANSWER_KEY; //insert
            }
            else
            {
                url = Config.Instance.TUGAS_SERVICE_URL() + Config.TUGAS_CHANGE_KEY; //update
            }
            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                ObservableCollection<TugasDetail> detail = JsonConvert.DeserializeObject<ObservableCollection<TugasDetail>>(e.Result);
                if (detail.Count > 0 && string.IsNullOrEmpty(detail[0].Link))
                {
                    MessageBox.Show("Tugas sudah di kumpulkan");
                    ViewDetailTugas(detail[0]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private TugasDetail DetailTugas()
        {
            if (detailTugas == null)
                detailTugas = new TugasDetail();

            detailTugas.Mhs = (Mahasiswa)SavedUser.Instance.User.ConvertUser();
            detailTugas.Tugas = selectedTugas.Id;
            return detailTugas;
        }

        private void textBoxLink_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (detailTugas != null && !string.IsNullOrEmpty(detailTugas.Link))
            {
                try
                {
                    var task = new Microsoft.Phone.Tasks.WebBrowserTask
                    {
                        Uri = new Uri(detailTugas.Link.Contains("http://") ? detailTugas.Link : "http://" + detailTugas.Link)
                    };

                    task.Show();
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }
        }
    
    }
}